import csv
from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QTableWidget,
    QTableWidgetItem, QGroupBox, QComboBox, QDateEdit, QLineEdit, QHeaderView,
    QFileDialog, QAbstractItemView, QMessageBox, QFormLayout, QWidget
)
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtCore import  QDate


class TransactionQueryDialog(QDialog):
    """交易详情对话框 - 独立模块"""

    def __init__(self, record, parent=None):
        super().__init__(parent)
        self.setWindowTitle("交易详情")
        self.setFixedSize(500, 400)
        self.setup_ui(record)

    def setup_ui(self, record):
        """初始化对话框界面"""
        layout = QVBoxLayout()

        # 交易基本信息
        basic_info = QGroupBox("基本信息")
        form_layout = QFormLayout()

        self.labels = {
            "日期": QLabel(record["tradeDate"].strftime("%Y-%m-%d %H:%M")),
            "交易类型": QLabel(record["tradeType"]),
            "交易金额": QLabel(f"¥{record['tradeMoney']:.2f}"),
            "交易ID": QLabel(record["transactionID"])
        }

        for key, label in self.labels.items():
            label.setStyleSheet("font-size: 15px; color: #495057;")
            form_layout.addRow(f"{key}:", label)

        # 突出显示金额颜色
        if record["tradeMoney"] > 0:
            self.labels["交易金额"].setStyleSheet("font-size: 15px; color: #28a745; font-weight: bold;")
        else:
            self.labels["交易金额"].setStyleSheet("font-size: 15px; color: #dc3545; font-weight: bold;")

        basic_info.setLayout(form_layout)
        layout.addWidget(basic_info)

        # 交易备注
        remark_info = QGroupBox("交易备注")
        remark_layout = QVBoxLayout()
        remark_text = record.get("remark", "") or "无备注信息"
        self.remark_label = QLabel(remark_text)
        self.remark_label.setStyleSheet("font-size: 15px; color: #6c757d; padding: 10px;")
        self.remark_label.setWordWrap(True)
        remark_layout.addWidget(self.remark_label)
        remark_info.setLayout(remark_layout)
        layout.addWidget(remark_info)
        layout.addStretch()

        # 操作按钮
        btn_box = QHBoxLayout()
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        close_btn.setStyleSheet("""
            QPushButton {
                background-color: #6c757d;
                color: white;
                padding: 8px 20px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #5a6268;
            }
        """)
        btn_box.addStretch()
        btn_box.addWidget(close_btn)
        layout.addLayout(btn_box)

        self.setLayout(layout)


class TransactionHistoryTab(QWidget):
    """交易记录查询选项卡 - 独立模块"""

    def __init__(self, card_id, db_utils):
        """
        初始化交易记录查询
        :param card_id: 银行卡号
        :param db_utils: DBUtils实例
        """
        super().__init__()
        self.card_id = card_id
        self.db = db_utils
        self.current_page = 1
        self.page_size = 10
        self.total_transactions = 0
        self.setup_ui()
        self.load_transaction_types()
        self.load_transactions()

    def setup_ui(self):
        """初始化界面"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(15)

        # 标题
        title = QLabel(f"交易记录查询 - 卡号: {self.card_id}")
        title.setStyleSheet("font-size: 16px; font-weight: bold; color: #2c3e50;")
        main_layout.addWidget(title)

        # 分隔线
        separator = QLabel()
        separator.setFixedHeight(1)
        separator.setStyleSheet("background-color: #e0e0e0;")
        main_layout.addWidget(separator)

        # ===== 查询面板 =====
        filter_group = QGroupBox("查询条件")
        filter_layout = QHBoxLayout()

        # 交易类型筛选
        type_layout = QVBoxLayout()
        type_layout.addWidget(QLabel("交易类型:"))
        self.type_combo = QComboBox()
        self.type_combo.setFixedWidth(150)
        type_layout.addWidget(self.type_combo)
        filter_layout.addLayout(type_layout)

        # 日期范围
        date_layout = QVBoxLayout()
        date_layout.addWidget(QLabel("日期范围:"))
        date_range_layout = QHBoxLayout()
        self.start_date = QDateEdit()
        self.start_date.setCalendarPopup(True)
        self.start_date.setDate(QDate.currentDate().addMonths(-1))
        self.end_date = QDateEdit()
        self.end_date.setCalendarPopup(True)
        self.end_date.setDate(QDate.currentDate())
        date_range_layout.addWidget(self.start_date)
        date_range_layout.addWidget(QLabel("至"))
        date_range_layout.addWidget(self.end_date)
        date_layout.addLayout(date_range_layout)
        filter_layout.addLayout(date_layout)

        # 金额范围
        amount_layout = QVBoxLayout()
        amount_layout.addWidget(QLabel("金额范围:"))
        amount_range_layout = QHBoxLayout()
        self.min_amount = QLineEdit()
        self.min_amount.setPlaceholderText("最小金额")
        self.min_amount.setFixedWidth(100)
        self.max_amount = QLineEdit()
        self.max_amount.setPlaceholderText("最大金额")
        self.max_amount.setFixedWidth(100)
        amount_range_layout.addWidget(self.min_amount)
        amount_range_layout.addWidget(QLabel("~"))
        amount_range_layout.addWidget(self.max_amount)
        amount_layout.addLayout(amount_range_layout)
        filter_layout.addLayout(amount_layout)

        # 操作按钮
        btn_layout = QVBoxLayout()
        self.query_btn = QPushButton("查询")
        self.query_btn.setFixedWidth(100)
        self.query_btn.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                font-weight: bold;
                padding: 8px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #0069d9;
            }
        """)
        self.query_btn.clicked.connect(self.load_transactions)

        self.export_btn = QPushButton("导出CSV")
        self.export_btn.setFixedWidth(100)
        self.export_btn.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                font-weight: bold;
                padding: 8px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #218838;
            }
        """)
        self.export_btn.clicked.connect(self.export_to_csv)

        btn_layout.addWidget(self.query_btn)
        btn_layout.addWidget(self.export_btn)
        btn_layout.addStretch()
        filter_layout.addLayout(btn_layout)
        filter_group.setLayout(filter_layout)
        main_layout.addWidget(filter_group)

        # ===== 交易记录表格 =====
        self.transaction_table = QTableWidget()
        self.transaction_table.setColumnCount(5)
        self.transaction_table.setHorizontalHeaderLabels(["交易时间", "交易类型", "交易金额", "交易ID", "操作"])
        self.transaction_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.transaction_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.transaction_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.transaction_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
        self.transaction_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
        self.transaction_table.horizontalHeader().setStyleSheet("QHeaderView::section { background-color: #e9ecef; }")
        self.transaction_table.verticalHeader().setVisible(False)
        self.transaction_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.transaction_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        main_layout.addWidget(self.transaction_table)

        # ===== 分页控制 =====
        page_layout = QHBoxLayout()

        # 分页信息
        self.page_info = QLabel("")
        self.page_info.setStyleSheet("font-size: 14px;")
        page_layout.addWidget(self.page_info)
        page_layout.addStretch()

        # 分页按钮
        self.prev_btn = QPushButton("上一页")
        self.prev_btn.setFixedWidth(100)
        self.prev_btn.clicked.connect(self.previous_page)
        page_layout.addWidget(self.prev_btn)

        self.next_btn = QPushButton("下一页")
        self.next_btn.setFixedWidth(100)
        self.next_btn.clicked.connect(self.next_page)
        page_layout.addWidget(self.next_btn)

        # 总金额统计
        self.total_label = QLabel("")
        self.total_label.setStyleSheet("font-size: 15px; font-weight: bold; color: #343a40;")
        page_layout.addWidget(self.total_label)

        main_layout.addLayout(page_layout)

    def load_transaction_types(self):
        """加载交易类型选项"""
        self.type_combo.addItem("所有类型", "")
        self.type_combo.addItem("存款", "存款")
        self.type_combo.addItem("取款", "取款")
        self.type_combo.addItem("转账转入", "转账转入")
        self.type_combo.addItem("转账转出", "转账转出")
        self.type_combo.addItem("余额转入", "余额转入")

    def build_query(self, count_query=False):
        """构建数据库查询语句"""
        # 基础查询
        if count_query:
            query = "SELECT COUNT(*) AS total FROM tradeinfo"
        else:
            query = """
            SELECT tradeDate, tradeType, tradeMoney, transactionID, remark
            FROM tradeinfo
            """

        # 添加WHERE条件
        conditions = ["cardID = %s"]
        params = [self.card_id]

        # 交易类型筛选
        trade_type = self.type_combo.currentData() if self.type_combo.currentIndex() > 0 else None
        if trade_type:
            conditions.append("tradeType = %s")
            params.append(trade_type)

        # 日期范围筛选
        start_date = self.start_date.date().toString("yyyy-MM-dd")
        end_date = self.end_date.date().addDays(1).toString("yyyy-MM-dd")  # 包含结束日期
        conditions.append("tradeDate BETWEEN %s AND %s")
        params.extend([start_date, end_date])

        # 金额范围筛选
        min_amount = self.min_amount.text()
        max_amount = self.max_amount.text()
        if min_amount:
            conditions.append("tradeMoney >= %s")
            params.append(float(min_amount))
        if max_amount:
            conditions.append("tradeMoney <= %s")
            params.append(float(max_amount))

        # 组合条件
        where_clause = " WHERE " + " AND ".join(conditions)

        # 最终查询
        if count_query:
            return query + where_clause, params

        # 添加排序
        query += where_clause
        query += " ORDER BY tradeDate DESC"

        # 添加分页限制
        if not count_query:
            offset = (self.current_page - 1) * self.page_size
            query += f" LIMIT {self.page_size} OFFSET {offset}"

        return query, params

    def load_transactions(self):
        """从数据库加载交易记录"""
        # 获取总记录数
        count_query, count_params = self.build_query(count_query=True)
        count_result = self.db.execute_query(count_query, count_params)

        if not count_result:
            QMessageBox.warning(self, "查询错误", "无法获取交易记录总数")
            return

        self.total_transactions = count_result[0]['total']

        # 获取当前页记录
        query, params = self.build_query()
        transactions = self.db.execute_query(query, params)

        if transactions is None:
            QMessageBox.warning(self, "查询错误", "获取交易记录时出错")
            return

        # 更新表格
        self.update_transaction_table(transactions)

        # 更新分页信息
        self.update_page_info()

    def update_transaction_table(self, transactions):
        """更新交易记录表格"""
        self.transaction_table.setRowCount(len(transactions))
        total_income = 0
        total_expense = 0

        for row, transaction in enumerate(transactions):
            # 交易时间
            trade_date = transaction["tradeDate"]
            time_item = QTableWidgetItem(trade_date.strftime("%Y-%m-%d %H:%M"))

            # 交易类型
            type_item = QTableWidgetItem(transaction["tradeType"])

            # 交易金额
            money = transaction["tradeMoney"]
            money_item = QTableWidgetItem(f"¥{abs(money):.2f}")
            if money > 0:
                money_item.setForeground(QBrush(QColor("#28a745")))  # 绿色收入
                total_income += money
            else:
                money_item.setForeground(QBrush(QColor("#dc3545")))  # 红色支出
                total_expense += money

            # 交易ID
            trans_id = transaction.get("transactionID", "")
            trans_id_item = QTableWidgetItem(trans_id if trans_id else "-")

            # 操作按钮
            detail_btn = QPushButton("查看详情")
            detail_btn.setStyleSheet("""
                QPushButton {
                    background-color: #17a2b8;
                    color: white;
                    font-weight: bold;
                    padding: 4px 8px;
                    border-radius: 3px;
                }
                QPushButton:hover {
                    background-color: #138496;
                }
            """)
            detail_btn.clicked.connect(lambda _, t=transaction: self.show_transaction_detail(t))

            # 添加到表格
            self.transaction_table.setItem(row, 0, time_item)
            self.transaction_table.setItem(row, 1, type_item)
            self.transaction_table.setItem(row, 2, money_item)
            self.transaction_table.setItem(row, 3, trans_id_item)
            self.transaction_table.setCellWidget(row, 4, detail_btn)

        # 更新总计
        self.total_label.setText(
            f"总收入: ¥{total_income:.2f} | 总支出: ¥{abs(total_expense):.2f} | 收支差额: ¥{(total_income + total_expense):.2f}")

    def update_page_info(self):
        """更新分页信息"""
        start = (self.current_page - 1) * self.page_size + 1
        end = min(self.current_page * self.page_size, self.total_transactions)
        self.page_info.setText(f"显示 {start}-{end} 条记录，共 {self.total_transactions} 条")

        # 更新按钮状态
        self.prev_btn.setEnabled(self.current_page > 1)
        self.next_btn.setEnabled(self.current_page * self.page_size < self.total_transactions)

    def previous_page(self):
        """上一页"""
        if self.current_page > 1:
            self.current_page -= 1
            self.load_transactions()

    def next_page(self):
        """下一页"""
        if self.current_page * self.page_size < self.total_transactions:
            self.current_page += 1
            self.load_transactions()

    def show_transaction_detail(self, transaction):
        """显示交易详情"""
        dialog = TransactionQueryDialog(transaction, self)
        dialog.exec_()

    def export_to_csv(self):
        """导出数据到CSV文件"""
        # 获取所有符合条件的记录（不分页）
        query, params = self.build_query()
        query = query.replace(f"LIMIT {self.page_size} OFFSET {(self.current_page - 1) * self.page_size}", "")
        transactions = self.db.execute_query(query, params)

        if not transactions:
            QMessageBox.warning(self, "导出失败", "没有可导出的交易记录")
            return

        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出交易记录", "", "CSV文件 (*.csv)")

        if file_path:
            try:
                with open(file_path, 'w', newline='', encoding='utf-8-sig') as file:
                    writer = csv.writer(file)
                    # 写入表头
                    writer.writerow(["交易时间", "交易类型", "交易金额", "交易ID", "备注"])

                    # 写入数据
                    for trans in transactions:
                        writer.writerow([
                            trans["tradeDate"].strftime("%Y-%m-%d %H:%M"),
                            trans["tradeType"],
                            trans["tradeMoney"],
                            trans.get("transactionID", ""),
                            trans.get("remark", "") or ""
                        ])

                QMessageBox.information(self, "导出成功", f"交易记录已成功导出到:\n{file_path}")
            except Exception as e:
                QMessageBox.critical(self, "导出失败", f"导出交易记录时出错:\n{str(e)}")


class TransactionQueryManager:
    """交易记录查询管理器 - 独立模块"""

    def __init__(self, card_id, db_utils):
        """
        初始化交易记录查询管理器
        :param card_id: 银行卡号
        :param db_utils: DBUtils实例
        """
        self.card_id = card_id
        self.db = db_utils
        self.transaction_tab = None

    def show_query_window(self, parent=None):
        """显示交易记录查询窗口"""
        if not self.transaction_tab:
            self.transaction_tab = TransactionHistoryTab(self.card_id, self.db)

        # 创建对话框
        dialog = QDialog(parent)
        dialog.setWindowTitle(f"交易记录查询 - 卡号: {self.card_id}")
        dialog.setMinimumSize(1200, 800)

        layout = QVBoxLayout(dialog)
        layout.addWidget(self.transaction_tab)

        # 添加关闭按钮
        btn_close = QPushButton("关闭")
        btn_close.clicked.connect(dialog.accept)
        btn_close.setStyleSheet("""
            QPushButton {
                background-color: #6c757d;
                color: white;
                padding: 8px 20px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #5a6268;
            }
        """)
        layout.addWidget(btn_close)

        dialog.exec_()


# 集成到现有系统的方法
def integrate_transaction_query(card_id, db_utils):
    """将交易记录查询功能集成到现有系统"""
    query_manager = TransactionQueryManager(card_id, db_utils)
    return query_manager